package com.htj.admin.controller;


import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.htj.admin.domain.Order;
import com.htj.admin.domain.dto.AliPay;
import com.htj.admin.service.FoodServiceInf;
import com.htj.admin.service.FrontUserServiceInf;
import com.htj.admin.service.OrderServiceInf;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("alipay")
public class AliPayController {

    @Autowired
    private OrderServiceInf orderServiceInf;
    @Autowired
    private FrontUserServiceInf frontUserServiceInf;

    @GetMapping("/pay")
    public String pay(AliPay aliPay) {
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(aliPay.getSubject(), aliPay.getTraceNo(), aliPay.getTotalAmount(), "");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }


    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String subject = params.get("subject");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                String vipId = getVId(subject);
                String userId = getUId(subject);

                if("v".equals(subject.substring(0,1))){
                    frontUserServiceInf.changeVip(vipId,userId);
                }else{
                    // 更新订单未已支付
                    HashMap<String, String> map = new HashMap<>();
                    map.put("pay","1");
                    map.put("orderNo",tradeNo);
                    map.put("status","1");
                    //改变订单状态
                    orderServiceInf.changePay(map);
                }
                System.out.println("订单号:"+tradeNo);
                System.out.println("创建时间:"+gmtPayment);
            }
        }
        return "success";
    }
    private String getVId(String str){
        StringBuilder sb = new StringBuilder();
        for(int i = 1;i < str.length();i++){
            if(str.charAt(i) != 'u'){
                sb.append(str.charAt(i));
            }else{
                break;
            }
        }
        return sb.toString();
    }
    private String getUId(String str){
        StringBuilder sb = new StringBuilder();
        for(int i = 1;i < str.length();i++){
            if(str.charAt(i) == 'u'){
                sb.append(str.substring(i+1));
                break;
            }
        }
        return sb.toString();
    }
}
